using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MSIACCSL2.ViewModels;
using WcfService1.DTO;

namespace MSIACCSL2.Views.FormSearch
{
    public partial class CustomerSearch : ChildWindow
    {
        private bool _isInitialLoad;

        public CustomerSearchViewModel VM
        {
            get
            {
                return this.DataContext as CustomerSearchViewModel;
            }
        }

        public CustomerDTO Customer { get; set; }
        public CustomerSearch()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SupplierSearch_Loaded);
            this.GotFocus += new RoutedEventHandler(SupplierSearch_GotFocus);
            txtCustomerName.GotFocus += new RoutedEventHandler(txtCustomerName_GotFocus);
        }

        void txtCustomerName_GotFocus(object sender, RoutedEventArgs e)
        {
            txtCustomerName.SelectAll();
        }

        void SupplierSearch_GotFocus(object sender, RoutedEventArgs e)
        {
            if (_isInitialLoad)
            {
                txtCustomerName.Focus();
                _isInitialLoad = false;
            }
        }

        void SupplierSearch_Loaded(object sender, RoutedEventArgs e)
        {
            _isInitialLoad = true;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void txtCustomerName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
        	if (e.Key == Key.Enter)
                VM.SearchCustomer((sender as TextBox).Text);
            else if (e.Key == Key.Down)
                dg1.Focus();
        }

        private void DataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (dg1.SelectedItem != null)
                Customer = dg1.SelectedItem as CustomerDTO;
        }

     
        private void dg1_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (dg1.SelectedIndex != 0 && dg1.SelectedIndex != VM.Customers.Count -1)
                    dg1.SelectedIndex -= 1;
                this.Close();
            }
            else if (e.Key == Key.Escape)
            {
                txtCustomerName.Focus();
            }
        }

    }
}

